package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.*;
import com.project.mapper.*;
import com.project.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ProductServiceImpl implements IProductService {
    @Autowired
    private IProductMapper productMapper;

    @Autowired
    private IBuyCarMapper buyCarMapper;

    @Autowired
    private IBuyOrderMapper orderMapper;

    @Autowired
    private IBuyOrderInfoMapper buyOrderInfoMapper;

    @Autowired
    private ISaleCarMapper saleCarMapper;

    @Autowired
    private ISaleOrderMapper saleOrderMapper;

    @Autowired
    private ISaleOrderInfoMapper saleOrderInfoMapper;


    /**
     * 添加商品,操作（隐藏表单 add/update）
     * 判断操作的值，如果是update，那么，判断该采购车中是否存在该商品，
     * 如果存在，修改采购车中的采购数量（累加），
     * 如果不存在，则新增采购车中的采购商品。
     *
     * @param product 产品对象
     */
    @Override
    public void add(ProductBean product, Integer num, Integer userId) {
        //判断商品id是否重复
        ProductBean productBean = productMapper.selectById(product.getId());
        if (productBean == null) {
            //如果商品没有查询到，那么添加商品
            productMapper.insert(product);
            //添加购物车
            buyCarMapper.insert(new BuyCarBean(product.getId(), num, product.getBuyPrice(), userId));
        } else {
            //商品在库存中存在，判断购物车中是否有该商品
            QueryWrapper<BuyCarBean> qw = new QueryWrapper<>();
            qw.eq("fk_productId", product.getId());
            qw.eq("fk_userId", userId);
            BuyCarBean buyCarBean = buyCarMapper.selectOne(qw);
            if (buyCarBean == null) {
                //添加购物车
                buyCarMapper.insert(new BuyCarBean(product.getId(), num, product.getBuyPrice(), userId));
            } else {
                //如果不为null,那就就修改原来采购车中商品的数量
                buyCarBean.setNum(buyCarBean.getNum() + num);
                buyCarMapper.updateById(buyCarBean);
            }
        }
    }

    @Override
    public IPage<ProductBean> findByItem(Integer pageNO, String name,
                                         Integer startNum, Integer endNum,
                                         String salePrice, String type) {
        QueryWrapper<ProductBean> qw = new QueryWrapper<>();
        if (name != null && name.length() != 0) {
            qw.like("p_name", name);
        }
        if (startNum != null && startNum >= 0) {
            qw.ge("p_num", startNum);
        }
        if (endNum != null && endNum >= 0) {
            qw.le("p_num", endNum);
        }
        if (!"不限".equals(salePrice)) {
            qw.isNull("p_salePrice");
        }
        if (type != null && type.length() != 0) {
            qw.eq("p_type", type);
        }
        return productMapper.selectPage(new Page<>(pageNO, 3), qw);
    }

    @Override
    public ProductBean findById(Integer id) {
        return productMapper.selectById(id);
    }

    @Override
    public void updateSalePrice(Integer id, Integer newSalePrice) {
        ProductBean byId = findById(id);
        byId.setSalePrice(newSalePrice);
        productMapper.updateById(byId);
    }

    @Override
    public void inKu(BuyOrderBean orderBean) {
        //添加采购订单
        orderMapper.insert(orderBean);
        //按采购员的id（登录用户id）查询采购车信息
        QueryWrapper<BuyCarBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId", orderBean.getUserId());
        //得到采购车集合
        List<BuyCarBean> buyCarBeans = buyCarMapper.selectList(qw);
        //遍历采购车，
        for (int i = 0; i < buyCarBeans.size(); i++) {
            //循环添加采购的明细信息，
            BuyCarBean carBean = buyCarBeans.get(i);
            buyOrderInfoMapper.insert(new BuyOrderInfoBean(orderBean.getId(),
                    carBean.getProductId(), carBean.getPrice(), carBean.getNum()));
            //循坏修改库存商品的库存数量（累加）、以及最新的采购价
            ProductBean productBean = productMapper.selectById(carBean.getProductId());
            productBean.setNum(productBean.getNum() + carBean.getNum());
            productBean.setBuyPrice(carBean.getPrice());
            productMapper.updateById(productBean);
        }
        //根据采购员id清空购物车
        QueryWrapper<BuyCarBean> qw2 = new QueryWrapper<>();
        qw2.eq("fk_userId", orderBean.getUserId());
        buyCarMapper.delete(qw2);
    }

    @Override
    public void outKu(SaleOrderBean saleOrderBean) {
        //1.添加销售订单
        saleOrderMapper.insert(saleOrderBean);
        //2.通过用户id查询销售车商品集合
        List<SaleCarBean> scBean = saleCarMapper.findById(saleOrderBean.getUserId());
        //3.遍历采购车，循环添加销售明细信息，
        for (int i = 0; i < scBean.size(); i++) {
            SaleCarBean item = scBean.get(i);
            SaleOrderInfoBean saleOrderInfoBean = new SaleOrderInfoBean(saleOrderBean.getId(), item.getProductId(), item.getProduct().getSalePrice(), item.getNum());
            saleOrderInfoMapper.insert(saleOrderInfoBean);
            //3.1 修改库存商品的库存数量（累减）
            ProductBean productBean = productMapper.selectById(item.getProductId());
            productBean.setNum(productBean.getNum() - item.getNum());
            productMapper.updateById(productBean);
        }
        //4.根据采购员id清空销售车
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("fk_userId", saleOrderBean.getUserId());
        saleCarMapper.delete(qw);
    }
}
